<?php


namespace app\index\model;


use think\Model;

class MemberCostHistory extends Model
{
    protected $type=[0=>'消费',1=>'充值'];

    public static function add($data)
    {
        $MemberCostHistoryClass=new self();
        $result=$MemberCostHistoryClass->save($data);
        if (!$result){
            return ['status'=>false,'result'=>'历史记录添加失败'];
        }else{
            return ['status'=>true,'result'=>'添加成功'];
        }
    }

    public static function getRecordById($search_param,$page_param)
    {
        $memberHistoryClass=new self();
        $CustomerClass=new Customer();
        if (empty($search_param['id'])){
            return ['status'=>false,'result'=>'获取不到用户信息'];
        }
        $where['mh.customer_id']=$search_param['id'];
        if (!empty($search_param['type'])){
            $where['mh.type']=$search_param['type'];
        }
        $data=$memberHistoryClass->alias('mh')
            ->join('order o','mh.order_id=o.id','left')
            ->where($where)->where(['mh.del_flag'=>0])
            ->order('mh.create_time desc')
            ->field('if(mh.type=0,round(mh.balance,2),null) consumption,if(mh.type=1,round(mh.balance),null) recharge,mh.discount,o.order_id,mh.create_time')
            ->paginate($page_param['page_size'],false,['page'=>$page_param['page_num']]);

        $total_data=$CustomerClass->alias('c')
            ->join('member m','c.id=m.customer_id','left')
            ->join('member_cost_history mch','c.id=mch.customer_id','left')
            ->where(['c.id'=>$search_param['id'],'mch.del_flag'=>0])
            ->field('sum(IFNULL(mch.balance,0)) total,mch.type,c.nick_name,c.email,m.balance')
            ->group('mch.type')
            ->select()->toArray();
        $recharge_total=0;
        $consumption_total=0;
        foreach ($total_data as $key=>$value){
            if($value['type']===1){
                $recharge_total=round($value['total'],2);
            }else if($value['type']===0){
                $consumption_total=round($value['total'],2);
            }
        }
        $history_data=$data->items();
        $total=$data->total();
        $customer_data=['customer_name'=>$total_data[0]['nick_name'],'email'=>$total_data[0]['email'],'recharge'=>$recharge_total,'consumption_total'=>$consumption_total,'balance'=>$total_data[0]['balance']];

        return ['status'=>true,'result'=>['data'=>$history_data,'total'=>$total,'customer_data'=>$customer_data,'type_list'=>$memberHistoryClass->type]];
    }
}